//
//  KqMLocation.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/10.
//

#import "KqMLocation.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "KqTool.h""


#define PI 3.1415926

static KqMLocation *gMLocation = nil;

@interface KqMLocation () <AMapLocationManagerDelegate>

@property (nonatomic, strong) AMapLocationManager *LocationManager;

@end

@implementation KqMLocation


+(KqMLocation *)sharedInstance
{
    if (gMLocation == nil) {
        gMLocation = [[self alloc] init];
    }
    return gMLocation;
}

+(id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t gPredicate;
    dispatch_once(&gPredicate, ^{
        gMLocation = [super allocWithZone:zone];
    });
    
    return gMLocation;
}

+ (id)copyWithZone:(NSZone *)zone
{
    return gMLocation;
}

+ (id)mutableCopyWithZone:(NSZone *)zone
{
    return gMLocation;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        //正式
        [AMapServices sharedServices].apiKey = @"1b54d00713bf136ae20d3b22f309979c";
    
        //取定位
        _LocationManager = [[AMapLocationManager alloc] init];
        _LocationManager.delegate = self;
        _LocationManager.distanceFilter = 3;
        
    }
    return self;
}

#pragma mark 启动定位

- (BOOL)startGetLocation
{
    self.latitude = nil;
    self.longitude = nil;
    self.strAdress = nil;
    //每次都进行判断
    //在加一次提醒  这个地方需要后续的更新
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        // 定位管理器 开始更新位置
        [_LocationManager stopUpdatingLocation];
        [_LocationManager setLocatingWithReGeocode:YES];
        [_LocationManager startUpdatingLocation];
        return YES;
        
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请去系统设置里开启管工厂云的定位权限" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        }];
        [alert addAction:cancelAction];
        UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:confirmAction];
        if ([KqTool getNav]) {
            [[KqTool getNav] presentViewController:alert animated:YES completion:nil];
        }else{
            [[KqTool getRootController] presentViewController:alert animated:YES completion:nil];
        }
        
        return NO;
    }
}

-(void)getLocation{
    self.latitude = nil;
    self.longitude = nil;
    self.strAdress = nil;
    //每次都进行判断
    //在加一次提醒  这个地方需要后续的更新
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        // 定位管理器 开始更新位置
        [_LocationManager stopUpdatingLocation];
        [_LocationManager setLocatingWithReGeocode:YES];
        [_LocationManager startUpdatingLocation];
    }
}

-(BOOL)isOpenPermission{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        return YES;
    } else {
        return NO;
    }
}

- (void)stopLocation{
    [_LocationManager stopUpdatingLocation];
}

#pragma mark - AMapLocationManagerDelegate

//申请后台定位回调
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestWhenInUseAuthorization];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    if (reGeocode)
    {
        self.strAdress = reGeocode.formattedAddress ? reGeocode.formattedAddress : reGeocode.POIName ? reGeocode.POIName : [NSString stringWithFormat:@"%@%@%@",reGeocode.province,reGeocode.city,reGeocode.country];
        if(self.strAdress && self.strAdress.length > 0){
            self.longitude = [NSString stringWithFormat:@"%lf",location.coordinate.longitude];
           self.latitude = [NSString stringWithFormat:@"%lf",location.coordinate.latitude];
        }
    }
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    if (error.code == AMapLocationErrorRiskOfFakeLocation) {
//        NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.userInfo);
        
        //存在虚拟定位的风险的定位结果
        __unused CLLocation *riskyLocateResult = [error.userInfo objectForKey:@"AMapLocationRiskyLocateResult"];
        //存在外接的辅助定位设备
        __unused NSDictionary *externalAccressory = [error.userInfo objectForKey:@"AMapLocationAccessoryInfo"];
    }
    
    if ([UIDevice currentDevice].systemVersion.floatValue < 10.0) {
        if ([error code] != kCLErrorLocationUnknown) {
            self.latitude = nil;
            self.longitude = nil;
            self.strAdress = nil;
        }
    }else{
        self.latitude = nil;
        self.longitude = nil;
        self.strAdress = nil;
    }
}

@end
